package com.zcf.shiro.web.controller;

import com.zcf.shiro.web.bean.User;
import explorer.web.rest.RestResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @author zhaochaofeng
 * @date 2020/6/17 13:26
 */
@Controller
public class LoginController extends CommonController {

    @GetMapping({"/login","/","index"})
    public String login() {
        User currUser = getLoginUser();
        if(currUser!=null)
        {
            if(hasRole("admin"))
            {
                return "redirect:manage/index";
            }else{
                return "redirect:member/index";
            }
        }else{
            return "login";
        }
    }

    @ResponseBody
    @PostMapping("/login")
    public RestResult login(@ModelAttribute User user) {
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        //给密码进行加密，盐值是账号
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                user.getId(),
                user.getPassword()
        );
        //必须设置成true后，才会在服务器重启后，用户登录状态不丢失
        usernamePasswordToken.setRememberMe(true);
        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(usernamePasswordToken);
        } catch (AuthenticationException e) {
            return RestResult.createFailedResult("用户名密码错误");
        } catch (AuthorizationException e) {
            return RestResult.createFailedResult("权限不足");
        }
        return RestResult.createSuccessResult("登录成功");
    }

    //注解验角色和权限
    @RequiresRoles("customer")
    @RequestMapping("/member/index")
    public String Memberindex() {
        return "/member/index";
    }

    //注解验角色和权限
    @RequiresRoles("admin")
    @RequestMapping("/manage/index")
    public String Manageindex() {
        return "/manage/index";
    }

}
